﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace KAsFrame.Common.Extensions
{
    public static class CommonExtensions
    {
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
        public static bool IsNullOrWhiteSpace(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        public static bool IsAny<T>(this List<T> ls)
        {
            return ls != null && ls.Any();
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string Md5Encryption(this string txt, MD5Length length = MD5Length.Length32)
        {
            byte[] sor = Encoding.UTF8.GetBytes(txt);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            var strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                //加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
                var xStr = string.Empty;
                switch (length)
                {
                    case MD5Length.Length32:
                        xStr = "x2";
                        break;
                    case MD5Length.Length48:
                        xStr = "x3";
                        break;
                    case MD5Length.Length64:
                        xStr = "x4";
                        break;
                }
                strbul.Append(result[i].ToString(xStr));
            }
            return strbul.ToString().ToUpper();
        }
    }

    public enum MD5Length
    {
        Length32,
        Length48,
        Length64
    }
}
